<?php
ignore_user_abort(true);
//set_time_limit(0);
$tablename='message';//判断的表名称
$sql_path='./sql.sql';//运行的sql语句
header('Content-Type:text/html; charset=utf-8');
//连接数据库
mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER, SAE_MYSQL_PASS) or die('数据库连接失败，请查看您的数据库是否已经初始化');
mysql_select_db(SAE_MYSQL_DB);
mysql_query("set names utf8");
$ret=  mysql_query("SHOW TABLES LIKE '$tablename'");
if(mysql_fetch_array($ret)){
    //显示错误提示
    echo "你已经安装过，不能重复安装!";
}else{
    createTable($sql_path);
    echo "安装成功";
}
//查询表是否存在
//创建表

//创建表
function createTable($sql_path,$dbcharset='utf8') {
        $sql = file_get_contents($sql_path);
        $sql = str_replace("\r", "\n",$sql);
        $ret = array();
        $num = 0;
        foreach (explode(";\n", trim($sql)) as $query) {
            $queries = explode("\n", trim($query));
            foreach ($queries as $query) {
                $ret[$num] .= $query[0] == '#' || $query[0] . $query[1] == '--' ? '' : $query;
            }
            $num++;
        }
        unset($sql);
        foreach ($ret as $query) {
            $query = trim($query);
            if ($query) {
                if (substr($query, 0, 12) == 'CREATE TABLE') {
                    $name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query);
                    $type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $query));
                    $type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
                    $query = preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $query) .
                            (mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type");
                }
               mysql_query($query);
            }
        }
    }
?>
